package com.geekgo.lucenepp.core.config.doc;

import org.apache.lucene.document.*;
import org.apache.lucene.util.BytesRef;

import java.util.ArrayList;
import java.util.List;

/**
 * document封装
 *
 * @author HeHaoyang
 * @create 2017-06-14 11:04
 **/
public class Documents {

    private Document document;


    public Documents() {
        document = new Document();
    }

    public void put(String key,Object val, String type, float boost){
        String value = "";
        if(val != null){
            value = val.toString();
        }
        addField(key, value, type, boost);
    }

    public Document getDocument(){
        return this.document;
    }



    /**
     *
     * @param name key
     * @param value val
     * @param boost 权重
     * @param type  字段类型
     */
    @SuppressWarnings("deprecation")
    public void addField(String name, String value,String type,float boost){
        List<Field> fields = new ArrayList<>();
        String type_ = type.toLowerCase();
        switch (type_) {
            case "int":
                int point_i = Integer.parseInt(value);
                fields.add(new IntPoint(name, point_i));
                fields.add(new StoredField(name, point_i));
                fields.add(new NumericDocValuesField(name, point_i));
                break;
            case "long":
                long point_l = Long.parseLong(value);
                fields.add(new LongPoint(name, point_l));
                fields.add(new StoredField(name, point_l));
                fields.add(new NumericDocValuesField(name, point_l));
                break;
            case "float":
                float point_f = Float.valueOf(value);
                fields.add(new FloatPoint(name, point_f));
                fields.add(new StoredField(name, point_f));
                break;
            case "binary":
                byte[] point_b = value.getBytes();
                fields.add(new BinaryPoint(name, point_b));
                fields.add(new StoredField(name, point_b));
                break;
            case "double":
                double point_d = Double.valueOf(value);
                fields.add(new DoublePoint(name, point_d));
                fields.add(new StoredField(name, point_d));
                break;
            case "string":
                fields.add(new StringField(name, value, Field.Store.YES));
                fields.add(new SortedDocValuesField(name, new BytesRef(value)));
                break;
            case "text":
                TextField textField = new TextField(name, value, Field.Store.YES);
                textField.setBoost(boost);
                fields.add(textField);
                break;
            default:
                break;
        }
        fields.forEach(field -> document.add(field));
    }
}
